<?php
/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2022/2/10
 * Time: 10:00 上午
 * description: Order.php
 */

namespace app\home\business;


use app\common\model\Address;
use app\common\model\OrderGoods;
use app\common\model\SpecGoods;
use think\Exception;
use think\exception\DbException;
use think\facade\Db;

class Order
{

    /**
     * 查询订单相关信息
     */
    public  static  function getOrderInfo(){

        //需要的查询的数据
        // 收件人信息
        $address = Address::where('user_id',session('user_info.id'))->select()->toArray();

        // 查询商品信息
        $cart_info = \app\common\model\Cart::with(['goods','spec_goods'])->where('user_id',session('user_info.id'))->where('is_selected',1)->select()->toArray();

        // 计算总价格/总件数
        $total_price = 0;
        $total_number = 0;
        foreach ($cart_info as $value) {
            $total_price += $value['number'] * $value['price'];
            $total_number += $value['number'];
        }
        return [
            'address' => $address,
            'goods_info' => $cart_info,
            'total_price' => $total_price,
            'total_number' => $total_number,
        ];
    }

    /**
     * @param $address_id
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public static function createOrder($address_id){
        // 第一步 判断有没有库存
        // 查询购买商品信息
        $buy_goods_info = \app\common\model\Cart::with(['goods','spec_goods'])->where('user_id',session('user_info.id'))->where('is_selected',1)->select()->toArray();
        foreach ($buy_goods_info as $value) {
            if ($value['number'] > $value['store_count'] - $value['store_frozen']) {
                throw new Exception('库存不足、请稍后购买');
            }
        }
        // 第二步 生成支付订单
        $user_id = session('user_info.id');
        if (!$user_id) {
            throw new Exception('请登录');
        }
        //        str_pad() 1-10000000
        $order_sn = date('YmdHis').rand(1000,9999);

        # 查询用户选择的配送地址信息
        $address_info = Address::find($address_id);
        # 计算总价格
        // 计算总价格/总件数
        $total_price = 0;
        foreach ($buy_goods_info as $value) {
            $total_price += $value['number'] * $value['price'];
        }
        // 启动事务
        Db::startTrans();
        try {
            // 添加订单基本信息
            $data = [
                'order_sn' => $order_sn,
                'user_id' => $user_id,
                'consignee' => $address_info['consignee'],
                'address' => $address_info['address'],
                'phone' => $address_info['phone'],
                'goods_price' => $total_price,
                'order_amount' => $total_price,
                'total_amount' => $total_price,
                'create_time' => time()
            ];
            $result = \app\common\model\Order::create($data);
            // 判断是否添加成功
            if (!$result) {
                throw new Exception('订单基本信息添加失败');
//                throw new Exception('下单失败');
            }

            // 添加订单商品信息
            // 构造数据
            $add_order_goods = [];
            $store_update = [];
            foreach ($buy_goods_info as $value) {
                $add_order_goods[] = [
                    'order_id' => $result->id,
                    'goods_id' => $value['goods_id'],
                    'spec_goods_id' => $value['spec_goods_id'],
                    'number' => $value['number'],
                    'goods_name' => $value['goods_name'],
                    'goods_logo' => $value['goods_logo'],
                    'goods_price' => $value['price'],
                    'spec_value_names' => $value['value_names'],
                    'create_time' => time(),
                ];
                $store_update[] = [
                    'id' => $value['spec_goods_id'],
                    'store_count' => $value['store_count'] - $value['number'],// 总库存 -购买数量
                    'store_frozen' => $value['store_frozen'] + $value['number'],// 冻结库存 + 购买数量
                    'update_time' => time(),
                ];
            }
            $order_goods_model = new OrderGoods();
            $goods_result = $order_goods_model->saveAll($add_order_goods);
            if (!$goods_result) {
                throw new Exception('下单失败');
            }

            // 第三步 清空所有购买的商品购物车数据
            $cart_ids = array_column($buy_goods_info,'id',NULL);
            $delete = \app\common\model\Cart::destroy($cart_ids);
            if (!$delete) {
                throw new Exception('下单失败');
            }
            // 冻结库存
            $spec_goods_model = new SpecGoods();
            $store_result = $spec_goods_model->saveAll($store_update);
            if (!$store_result) {
                throw new Exception('下单失败');
            }
            // 提交事务
            Db::commit();
            return [
                'order_id' => $result->id,
                'pay_price' => $total_price
            ];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new Exception($e->getMessage());
        }
    }

}